package bb.lanxing.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.model.LevelDataItem;
import bb.lanxing.model.database.User;
import bb.lanxing.model.database.UserCard;
import bb.lanxing.mvp.presetner.AreaSelectionPresenterImpl;
import bb.lanxing.mvp.presetner.i.AreaSelectionPresenter;
import bb.lanxing.mvp.view.i.AreaSelectionView;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.DateUtil;
import bb.lanxing.util.IdcardUtils;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.util.Validator;
import bb.lanxing.util.text.TextUtils;
import bb.lanxing.view.dialog.AreaSelectionDialog;
import bb.lanxing.view.BiciAlertDialogBuilder;

public class UserCardActivity extends BaseActivity implements AreaSelectionView {
    private EditText addressView;
    private TextView birthdayView;
    private EditText cardView;
    private TextView cityView;
    private EditText contactNameView;
    private EditText contactPhoneView;
    private User curUser;
    private EditText emailView;
    private TextView genderView;
    private View mBirthdayLayout;
    private View mGenderLayout;
    private View mSaveBtn;
    private View mSelectCity;
    private EditText nameView;
    private EditText phoneView;
    private AreaSelectionPresenter presenter;
    private UserCard userCard;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_card);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        initData();
        initView();
        requestUserCard();
    }

    private void initData() {
        User signinUser = App.getContext().getSigninUser();
        curUser = signinUser;
        userCard = UserCard.getUserCard(signinUser.getUid());
        if (userCard == null) {
            userCard = new UserCard();
        }
        presenter = new AreaSelectionPresenterImpl(this);
    }

    private void initView() {
        cardView.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                return;
            }
            pikeInfoFromCardNo(cardView.getText().toString());
        });
        refreshUI();
    }

    @Override
    public void onData(List<LevelDataItem> levelDataItemList) {
        if (levelDataItemList == null || levelDataItemList.isEmpty()) {
            return;
        }
        String province = userCard != null ? userCard.getProvince() : null;
        String city = userCard != null ? userCard.getCity() : null;
        AreaSelectionDialog.show(this, levelDataItemList, province, city, userCard != null ? userCard.getArea() : null).setOnAreaSelectionListener((p, c, d) -> {
            if (userCard != null) {
                userCard.setProvince(p);
                userCard.setCity(c);
                userCard.setArea(d);
            }
            cityView.setText(p + c + d);
        });
    }

    public void refreshUI() {
        runOnUiThread(() -> {
            int i;
            if (userCard != null) {
                if (!TextUtils.isEmptyOrNull(userCard.getName())) {
                    nameView.setText(userCard.getName());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getCardNo())) {
                    cardView.setText(userCard.getCardNo());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getGenderFormat())) {
                    genderView.setText(userCard.getGenderFormat());
                    genderView.setTag(userCard.getGender());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getBirthdayFormat())) {
                    birthdayView.setText(userCard.getBirthdayFormat());
                    birthdayView.setTag(userCard.getBirthday() * 1000);
                }
                if (!TextUtils.isEmptyOrNull(userCard.getPhone())) {
                    phoneView.setText(userCard.getPhone());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getEmail())) {
                    emailView.setText(userCard.getEmail());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getContactName())) {
                    contactNameView.setText(userCard.getContactName());
                }
                if (!TextUtils.isEmptyOrNull(userCard.getContactPhone())) {
                    contactPhoneView.setText(userCard.getContactPhone());
                }
                String str = (!TextUtils.isEmptyOrNull(userCard.getProvince()) ? userCard.getProvince() : "") + (!TextUtils.isEmptyOrNull(userCard.getCity()) ? userCard.getCity() : "") + (TextUtils.isEmptyOrNull(userCard.getArea()) ? "" : userCard.getArea());
                if (!TextUtils.isEmptyOrNull(str)) {
                    cityView.setText(str);
                    if (TextUtils.isEmptyOrNull(userCard.getAddressDetail())) {
                        return;
                    }
                    addressView.setText(userCard.getAddressDetail());
                    return;
                }
                cityView.setText(null);
                if (TextUtils.isEmptyOrNull(userCard.getAddress())) {
                    return;
                }
                addressView.setText(userCard.getAddress());
            } else if (curUser != null) {
                TextView textView = genderView;
                if (curUser.getGender() == 0) {
                    i = R.string.mine_profile_female;
                } else {
                    i = R.string.mine_profile_male;
                }
                textView.setText(getString(i));
                genderView.setTag(curUser.getGender() == 0 ? 2 : 1);
                phoneView.setText(curUser.getPhone());
                emailView.setText(curUser.getEmail());
            }
        });
    }

    public void pikeInfoFromCardNo(String cardNo) {
        if (Validator.isValidCardNo(cardNo)) {
            long birthTimestampByIdCard = IdcardUtils.getBirthTimestampByIdCard(cardNo);
            birthdayView.setText(DateUtil.format(birthTimestampByIdCard, 1));
            birthdayView.setTag(birthTimestampByIdCard);
            String genderByIdCard = IdcardUtils.getGenderByIdCard(cardNo);
            if ("M".equals(genderByIdCard)) {
                genderView.setText(R.string.mine_profile_male);
                genderView.setTag(1);
            } else if ("F".equals(genderByIdCard)) {
                genderView.setText(R.string.mine_profile_female);
                genderView.setTag(2);
            }
        }
    }

    private void onGenderClick() {
        showGenderDialog();
    }

    private void onBirthdayClick() {
        long longValue = birthdayView.getTag() != null ? (Long) birthdayView.getTag() : 0L;
        Calendar calendar = Calendar.getInstance();
        if (longValue > 0) {
            calendar.setTimeInMillis(longValue);
        } else {
            calendar.setTimeInMillis(System.currentTimeMillis());
        }
        showDatePickerDialog(calendar);
    }

    private void onSaveClick() {
        if (saveUserCard()) {
            MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_CARD_SAVE, null, 1);
            postUserCard();
        }
    }

    private void onSelectCity() {
        presenter.requestLevelData();
    }

    private void showGenderDialog() {
        new BiciAlertDialogBuilder(this).setTitle(R.string.mine_profile_dialog_title_choose_gender).setItems(new String[]{getString(R.string.mine_profile_male), getString(R.string.mine_profile_female)}, (dialog, which) -> {
            if (which == 0) {
                genderView.setText(R.string.mine_profile_male);
                genderView.setTag(1);
            } else if (which == 1) {
                genderView.setText(R.string.mine_profile_female);
                genderView.setTag(2);
            }
        }).show();
    }

    private void showDatePickerDialog(final Calendar calendar) {
        new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
            calendar.set(year, monthOfYear, dayOfMonth);
            long timeInMillis = calendar.getTimeInMillis();
            birthdayView.setText(DateUtil.format(timeInMillis, 1));
            birthdayView.setTag(timeInMillis);
        }, calendar.get(1), calendar.get(2), calendar.get(5)).show();
    }

    private boolean saveUserCard() {
        String name = nameView.getText().toString();
        String card = this.cardView.getText().toString();
        String charSequence = genderView.getText().toString();
        int intValue = genderView.getTag() != null ? (Integer) genderView.getTag() : 0;
        long longValue = birthdayView.getTag() != null ? (Long) birthdayView.getTag() : 0L;
        String phone = phoneView.getText().toString();
        String email = emailView.getText().toString();
        String address = addressView.getText().toString();
        String contact = contactNameView.getText().toString();
        String contactPhone = contactPhoneView.getText().toString();
        if (!TextUtils.isEmptyOrNull(name) && !Validator.isValidUsername(name)) {
            App.getContext().showMessage(R.string.mine_profile_username_not_valid);
            nameView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(card) && !Validator.isValidCardNo(card)) {
            App.getContext().showMessage(R.string.mine_profile_idcard_format_error);
            this.cardView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(charSequence) && TextUtils.isEmptyOrNull(charSequence)) {
            App.getContext().showMessage(R.string.mine_profile_gender_not_valid);
            genderView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(phone) && !Validator.isPhoneNumber(phone)) {
            App.getContext().showMessage(R.string.mine_profile_phone_not_valid);
            phoneView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(email) && !Validator.isValidEmail(email)) {
            App.getContext().showMessage(R.string.mine_profile_email_format_error);
            emailView.requestFocus();
            return false;
        } else if (TextUtils.isEmptyOrNull(address) || TextUtils.isEmptyOrNull(address.trim())) {
            App.getContext().showMessage(R.string.mine_profile_address_not_valid);
            addressView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(contact) && !Validator.isValidUsername(contact)) {
            App.getContext().showMessage(R.string.mine_profile_username_not_valid);
            contactNameView.requestFocus();
            return false;
        } else if (!TextUtils.isEmptyOrNull(contactPhone) && !Validator.isPhoneNumber(contactPhone)) {
            App.getContext().showMessage(R.string.mine_profile_phone_not_valid);
            contactPhoneView.requestFocus();
            return false;
        } else {
            if ((userCard != null && TextUtils.isEmptyOrNull(userCard.getProvince())) || TextUtils.isEmptyOrNull(userCard.getCity()) || TextUtils.isEmptyOrNull(userCard.getArea())) {
                App.getContext().showMessage(R.string.mine_profile_address_no_area);
                return false;
            }
            if (userCard == null) {
                userCard = new UserCard();
                userCard.setUserId(curUser.getUid());
            }
            if (!TextUtils.isEmptyOrNull(name)) {
                userCard.setName(name);
            }
            if (!TextUtils.isEmptyOrNull(card)) {
                userCard.setCardNo(card);
            }
            if (intValue != 0) {
                userCard.setGender(intValue);
            }
            if (longValue > 0) {
                userCard.setBirthday(longValue / 1000);
            }
            if (!TextUtils.isEmptyOrNull(phone)) {
                userCard.setPhone(phone);
            }
            if (!TextUtils.isEmptyOrNull(email)) {
                userCard.setEmail(email);
            }
            if (!TextUtils.isEmptyOrNull(address)) {
                userCard.setAddress(address);
                userCard.setAddressDetail(address);
            }
            if (!TextUtils.isEmptyOrNull(contact)) {
                userCard.setContactName(contact);
            }
            if (!TextUtils.isEmptyOrNull(contactPhone)) {
                userCard.setContactPhone(contactPhone);
            }
            userCard.save();
            return true;
        }
    }

    private void requestUserCard() {
        showMyProgressDialog();
        MyHttpClient.requestUserCard(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String string) {
                dismissLoadingDialog();
                try {
                    Long id = userCard.getId();
                    userCard = new UserCard(Objects.requireNonNull(JsonUtil.getObjectValue("data", new JSONObject(string))));
                    if (userCard.getCardId() > 0) {
                        if (id != null) {
                            userCard.setId(id);
                        }
                        userCard.save();
                        refreshUI();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponseFail(String errMsg) {
                super.onResponseFail(errMsg);
                dismissLoadingDialog();
            }
        });
    }

    private void postUserCard() {
        showMyProgressDialog();
        MyHttpClient.postUserCard(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String string) {
                dismissLoadingDialog();
                finish();
            }

            @Override
            public void onResponseFail(String errMsg) {
                super.onResponseFail(errMsg);
                dismissLoadingDialog();
            }
        }, userCard);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AreaSelectionPresenter areaSelectionPresenter = presenter;
        if (areaSelectionPresenter != null) {
            areaSelectionPresenter.destroy();
        }
    }

    private void bindView(View bindSource) {
        nameView = bindSource.findViewById(R.id.nameView);
        cardView = bindSource.findViewById(R.id.cardView);
        genderView = bindSource.findViewById(R.id.genderView);
        birthdayView = bindSource.findViewById(R.id.birthdayView);
        phoneView = bindSource.findViewById(R.id.phoneView);
        emailView = bindSource.findViewById(R.id.emailView);
        addressView = bindSource.findViewById(R.id.addressView);
        contactNameView = bindSource.findViewById(R.id.contactNameView);
        contactPhoneView = bindSource.findViewById(R.id.contactPhoneView);
        cityView = bindSource.findViewById(R.id.cityView);
        mGenderLayout = bindSource.findViewById(R.id.genderLayout);
        mBirthdayLayout = bindSource.findViewById(R.id.birthdayLayout);
        mSaveBtn = bindSource.findViewById(R.id.saveBtn);
        mSelectCity = bindSource.findViewById(R.id.selectCity);
        mGenderLayout.setOnClickListener(v -> onGenderClick());
        mBirthdayLayout.setOnClickListener(v -> onBirthdayClick());
        mSaveBtn.setOnClickListener(v -> onSaveClick());
        mSelectCity.setOnClickListener(v -> onSelectCity());
    }
}